package study.springboot.mvc.support.log;

import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.core.config.plugins.Plugin;
import org.apache.logging.log4j.core.pattern.ConverterKeys;
import org.apache.logging.log4j.core.pattern.LogEventPatternConverter;
import org.apache.logging.log4j.core.pattern.PatternConverter;

import java.net.InetAddress;

//Plugin 表示的是这是一个插件，name是名称，category为PatternConverter.CATEGORY（目前插件只有这个选择）ConverterKeys表示的就是自定义的参数,可以多个
@Plugin(name = "IpPatternConverter", category = PatternConverter.CATEGORY)
@ConverterKeys({"ip"})
public class Log4jIPConverter extends LogEventPatternConverter {

    private static final Log4jIPConverter INSTANCE = new Log4jIPConverter();

    //定义的这个类必须提供一个newInstance方法，参数是final String[] options，返回值为定义的类（对于是否是单例没有明确的要求）
    public static Log4jIPConverter newInstance(final String[] options) {
        return INSTANCE;
    }

    protected Log4jIPConverter() {
        super("ip", "");
    }

    @Override
    public void format(LogEvent event, StringBuilder builder) {
        String ip;
        try {
            ip = InetAddress.getLocalHost().getHostAddress();
        } catch (Exception ex) {
            ip = "unknown-ip";
        }
        builder.append(ip);
    }
}
